package gui;

import entities.Medium;
import entities.Movie;
import implementation.CentralManagerImpl;
import implementation.IOManagerImpl;
import implementation.MediumManagerImpl;
import implementation.MovieManagerImpl;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import managers.CentralManager;
import managers.MediumManager;
import managers.MovieManager;
import models.MediumTableModel;
import models.MovieTableModel;
import utilities.InvalidFormatException;

/**
 * Main Window to operate the whole application.
 *
 * @author Lucyia
 */
public class MainWindow extends javax.swing.JFrame {

    private MediumManager mediumMan = new MediumManagerImpl();
    private MovieManager movieMan = new MovieManagerImpl();
    private CentralManager centralMan = new CentralManagerImpl();
    private boolean searchFieldSelected = false;
    private String path = System.getProperty("user.dir");
    private int lastSelected = Integer.MAX_VALUE;
    private Medium chosenMedium = null;
    private WorkingDialog workingDialog = null;
    private JFrame mainWindow = this;
    private static final Logger log = Logger.getLogger(MainWindow.class.getName());
    private boolean applicationStarted = false;

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {

        utilities.DBUtils.openDBConnection();

        initComponents();
        refreshMediumTable();
        refreshMovieTable();

        SelectionListener listener = new SelectionListener(jTableMedia);
        jTableMedia.getSelectionModel().addListSelectionListener(listener);
        jTableMedia.getColumnModel().getSelectionModel().addListSelectionListener(listener);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jInternalFrame1 = new javax.swing.JInternalFrame();
        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jTextFieldFilmSearch = new javax.swing.JTextField();
        jButtonSearch = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableFilms = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableMedia = new javax.swing.JTable();
        jButtonAddMedium = new javax.swing.JButton();
        jButtonDeleteMedium = new javax.swing.JButton();
        addMovieButton = new javax.swing.JButton();
        deleteMovieButton = new javax.swing.JButton();
        jLandedButton = new javax.swing.JButton();
        jButtonMediumNote = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenuImport = new javax.swing.JMenu();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItemImport = new javax.swing.JMenuItem();
        jMenuItemExport = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItemExit = new javax.swing.JMenuItem();
        jMenu5 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();

        jInternalFrame1.setVisible(true);

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jMenuItem1.setText("jMenuItem1");

        jMenuItem4.setText("jMenuItem4");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextFieldFilmSearch.setText("Search for a film");
        jTextFieldFilmSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldFilmSearchMouseClicked(evt);
            }
        });
        jTextFieldFilmSearch.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFilmSearchFocusGained(evt);
            }
        });

        jButtonSearch.setText("Search");
        jButtonSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSearchActionPerformed(evt);
            }
        });

        jTableFilms.setModel(new MovieTableModel());
        jTableFilms.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTableFilms.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(jTableFilms);
        jTableFilms.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTableFilms.getColumnModel().getColumn(1).setPreferredWidth(40);
        jTableFilms.getColumnModel().getColumn(2).setPreferredWidth(17);
        jTableFilms.getColumnModel().getColumn(3).setPreferredWidth(17);
        jTableFilms.getColumnModel().getColumn(4).setPreferredWidth(7);
        jTableFilms.getColumnModel().getColumn(5).setPreferredWidth(30);
        jTableFilms.getColumnModel().getColumn(6).setPreferredWidth(30);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Medium list"));

        jTableMedia.setModel(new models.MediumTableModel());
        jTableMedia.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTableMedia.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableMediaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableMedia);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButtonAddMedium.setText("Add new medium");
        jButtonAddMedium.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddMediumActionPerformed(evt);
            }
        });

        jButtonDeleteMedium.setText("Delete medium");
        jButtonDeleteMedium.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteMediumActionPerformed(evt);
            }
        });

        addMovieButton.setText("Add movie");
        addMovieButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addMovieButtonActionPerformed(evt);
            }
        });

        deleteMovieButton.setText("Delete movie");
        deleteMovieButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMovieButtonActionPerformed(evt);
            }
        });

        jLandedButton.setText("Land / Return");
        jLandedButton.setEnabled(false);
        jLandedButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jLandedButtonActionPerformed(evt);
            }
        });

        jButtonMediumNote.setText("See / Change the note");
        jButtonMediumNote.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonMediumNoteActionPerformed(evt);
            }
        });

        jMenuImport.setText("File");
        jMenuImport.add(jSeparator1);

        jMenuItemImport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItemImport.setText("Import");
        jMenuItemImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemImportActionPerformed(evt);
            }
        });
        jMenuImport.add(jMenuItemImport);

        jMenuItemExport.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItemExport.setText("Export");
        jMenuItemExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExportActionPerformed(evt);
            }
        });
        jMenuImport.add(jMenuItemExport);
        jMenuImport.add(jSeparator2);

        jMenuItemExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItemExit.setText("Exit");
        jMenuItemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExitActionPerformed(evt);
            }
        });
        jMenuImport.add(jMenuItemExit);

        jMenuBar1.add(jMenuImport);

        jMenu5.setText("Help");
        jMenu5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu5ActionPerformed(evt);
            }
        });

        jMenuItem3.setText("Info");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu5.add(jMenuItem3);

        jMenuBar1.add(jMenu5);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLandedButton, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonAddMedium, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonMediumNote, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonDeleteMedium, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextFieldFilmSearch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 827, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addMovieButton, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteMovieButton, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonAddMedium, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLandedButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonMediumNote))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldFilmSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonSearch))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(deleteMovieButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(addMovieButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonDeleteMedium))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Searching movies by the name.
     *
     * @param evt event when clicked on Search Button
     */
    private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSearchActionPerformed
        String searchphrase = jTextFieldFilmSearch.getText().toLowerCase();

        List<Movie> allMoviesList = movieMan.getAllMovies();
        List<Movie> resultMoviesList = new ArrayList<>();
        for (Movie movie : allMoviesList) {
            if (movie.getTitle().toLowerCase().equals(searchphrase)) {
                resultMoviesList.add(movie);
            }
        }

        SearchResultPositive dg = new SearchResultPositive(this, true);
        dg.fillWindow(resultMoviesList);
        dg.setVisible(true);
    }//GEN-LAST:event_jButtonSearchActionPerformed

    /**
     * Adding a new medium.
     *
     * @param evt event when clicked on Add medium Button
     */
    private void jButtonAddMediumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddMediumActionPerformed
        NewMediumJDialog dialog = new NewMediumJDialog(this);
        dialog.setVisible(true);
        //log.info("New medium created");
    }//GEN-LAST:event_jButtonAddMediumActionPerformed

    /**
     * Deleting a medium. Tests if is any chosen. When not, the user is notified
     * to choose one.
     *
     * @param evt event when clicked on Delete medium Button
     */
    private void jButtonDeleteMediumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteMediumActionPerformed

        if (jTableMedia.getSelectedRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No medium chosen.", "Attention", 2);
            return;
        }

        String[] options = {"yes", "no"};
        if (JOptionPane.showOptionDialog(this, "Do you really want to delete chosen media?",
                "Are you sure?", JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, options, null) != 0) {
            return;
        }

        int index = jTableMedia.getSelectedRow();
        MediumTableModel model = (MediumTableModel) jTableMedia.getModel();
        Medium mediumToDelete = model.getMediumAt(index);

        List<Movie> moviesOnMedium = centralMan.getMoviesOnMedium(mediumToDelete);
        for (Movie m : moviesOnMedium) {
            movieMan.deleteMovie(m);
        }

        mediumMan.deleteMedium(mediumToDelete);

        model.removeMedium(mediumToDelete);
        jTableMedia.changeSelection(-1, -1, false, false);
        refreshMovieTable();
        refreshMediumTable();
    }//GEN-LAST:event_jButtonDeleteMediumActionPerformed
    /**
     * Adding a new movie to the chosen medium.
     *
     * @param evt event when clicked on Add movie Button
     */
    private void addMovieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addMovieButtonActionPerformed
        if (jTableMedia.getSelectedRowCount() == 0) {
            JOptionPane.showMessageDialog(this, "No medium chosen.", "Attention", 2);
        } else {
            NewMovieJDialog dialog = new NewMovieJDialog(this);
            Movie movie = dialog.showWindow();
            lastSelected = Integer.MAX_VALUE;
            refreshMovieTable();
        }
    }//GEN-LAST:event_addMovieButtonActionPerformed

    /**
     * Deleting a movie. Tests if is any chosen. When not, the user is notified
     * to choose one.
     *
     * @param evt event when clicked on Delete Selected Movie Button
     */
    private void deleteMovieButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMovieButtonActionPerformed
        int index = jTableFilms.getSelectedRow();
        if (index == -1) {
            JOptionPane.showMessageDialog(this, "No movie chosen.", "Attention", 2);
        } else {
            String[] options = {"yes", "no"};
            if (JOptionPane.showOptionDialog(this, "Do you really want to delete chosen movie?",
                    "Are you sure?", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, options, null) != 0) {
                return;
            }

            MovieTableModel model = (MovieTableModel) jTableFilms.getModel();
            Movie movieToDelete = model.getMovieAt(index);
            movieMan.deleteMovie(movieToDelete);
            model.removeMovie(movieToDelete);
        }
    }//GEN-LAST:event_deleteMovieButtonActionPerformed

    /**
     * Changing the attribute Landed of a chosen Medium.
     *
     * @param evt event when clicked on Landed Button
     */
    private void jLandedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLandedButtonActionPerformed
        int index = jTableMedia.getSelectedRow();

        if (index != -1) {
            MediumTableModel model = (MediumTableModel) jTableMedia.getModel();
            Medium medium = model.getMediumAt(index);
            medium.setLended(!medium.isLended());
            mediumMan.updateMedium(medium);
            model.fireTableRowsUpdated(index, index);
            setLandedButton(model.getMediumAt(index).isLended());
        }
    }//GEN-LAST:event_jLandedButtonActionPerformed

    private void jTextFieldFilmSearchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldFilmSearchMouseClicked
        //nothing to do here :)
    }//GEN-LAST:event_jTextFieldFilmSearchMouseClicked
    /**
     * Erases the text in the search field when clicked for the first time.
     *
     * @param evt event when clicked in the field
     */
    private void jTextFieldFilmSearchFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldFilmSearchFocusGained
        if (!searchFieldSelected) {
            jTextFieldFilmSearch.setText("");
            searchFieldSelected = true;
        }
    }//GEN-LAST:event_jTextFieldFilmSearchFocusGained

    /**
     * Exits the whole application
     *
     * @param evt event when clicked on Search Button
     */
    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExitActionPerformed
        //closes database connection
        utilities.DBUtils.closeDB();
        this.dispose();
    }//GEN-LAST:event_jMenuItemExitActionPerformed

    /**
     * Import.
     *
     * @param evt event when clicked on Import Button
     */
    private void jMenuItemImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemImportActionPerformed
        IOManagerImpl ioManager = new IOManagerImpl();
        final JFileChooser fc = new JFileChooser(path);
        fc.setFileFilter(new ODTFileFilter());
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            path = file.getPath();
            try {
                ioManager.importFromODF(file.toString());
                refreshMediumTable();
                refreshMovieTable();
                //log.append("Opening: " + file.getName() + "." + newline);
            } catch (InvalidFormatException ex) {
                //Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            //log.append("Open command cancelled by user." + newline);
        }
    }//GEN-LAST:event_jMenuItemImportActionPerformed

    /**
     * Export.
     *
     * @param evt event when clicked on Export Button
     */
    private void jMenuItemExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExportActionPerformed
        IOManagerImpl ioManager = new IOManagerImpl();
        final JFileChooser fc = new JFileChooser(path);
        fc.setFileFilter(new ODTFileFilter());
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            path = file.getPath();
            ioManager.exportToODF(file.toString());
        } else {
            //log.append("Open command cancelled by user." + newline);
        }
    }//GEN-LAST:event_jMenuItemExportActionPerformed

    private void jMenu5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu5ActionPerformed
    }//GEN-LAST:event_jMenu5ActionPerformed
    /**
     * Shows a dialog with info.
     *
     * @param evt event when clicked on Info Button
     */
    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        OKDialog helpDialog = new OKDialog(this, rootPaneCheckingEnabled);
        helpDialog.setTextToAppear("Aplication VideoDES-muni.");
        helpDialog.setTextInfo("See more at code.google.com/p/videodes-muni/");
        helpDialog.setVisible(true);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jTableMediaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableMediaMouseClicked
        //nothing
    }//GEN-LAST:event_jTableMediaMouseClicked

    /**
     * Allows to see or change the note of the medium
     *
     * @param evt event when clicked on See / Chanfe the note Button
     */
    private void jButtonMediumNoteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMediumNoteActionPerformed
        MediumNoteDialog dialog = new MediumNoteDialog(this, rootPaneCheckingEnabled);
        int index = jTableMedia.getSelectedRow();
        MediumTableModel model = (MediumTableModel) jTableMedia.getModel();
        Medium medium = model.getMediumAt(index);
        dialog.setMediumType(medium.getType().toString());
        dialog.setOldMediumNote(medium.getNote());

        dialog.setVisible(true);
    }//GEN-LAST:event_jButtonMediumNoteActionPerformed

    /**
     * Main method of the class.
     *
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainWindow().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addMovieButton;
    private javax.swing.JButton deleteMovieButton;
    private javax.swing.JButton jButtonAddMedium;
    private javax.swing.JButton jButtonDeleteMedium;
    private javax.swing.JButton jButtonMediumNote;
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JButton jLandedButton;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenu jMenuImport;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItemExit;
    private javax.swing.JMenuItem jMenuItemExport;
    private javax.swing.JMenuItem jMenuItemImport;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JTable jTableFilms;
    private javax.swing.JTable jTableMedia;
    private javax.swing.JTextField jTextFieldFilmSearch;
    // End of variables declaration//GEN-END:variables

    /**
     * Changes the old note to new note at medium.
     *
     * @param note the note that should be stored
     * @return true if the old note is different, false when the note didn't
     * change
     */
    public boolean setNewNoteToMedium(String note) {
        int index = jTableMedia.getSelectedRow();
        if (index != -1) {
            MediumTableModel mediumModel = (MediumTableModel) jTableMedia.getModel();
            Medium currentMedium = (Medium) mediumModel.getMediumAt(index);
            if (currentMedium.getNote().equals(note)) {
                return false;
            } else {
                currentMedium.setNote(note);
                mediumMan.updateMedium(currentMedium);
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * Setting a medium parameter to the medium
     *
     * @param movie
     */
    public void setMediumToMovie(Movie movie) {
        int index = jTableMedia.getSelectedRow();
        if (index != -1) {
            MediumTableModel mediumModel = (MediumTableModel) jTableMedia.getModel();
            Medium currentMedium = (Medium) mediumModel.getMediumAt(index);

            centralMan.putMovieOnMedium(movie, currentMedium);
            refreshMovieTable();
        }
    }

    /**
     * Creates medium with the medium manager.
     *
     * @param medium
     */
    public void sentMediumToDB(Medium medium) {
        mediumMan.createMedium(medium);
    }

    /**
     * Creates movie with the movie manager.
     *
     * @param movie
     */
    public void sentMovieToDB(Movie movie) {
        movieMan.createMovie(movie);
    }

    /**
     * refreshes the table with list of mediums
     */
    public void refreshMediumTable() {
        if (jTableMedia != null) {
            jTableMedia.removeAll();
            MediumTableModel model = (MediumTableModel) jTableMedia.getModel();
            List<Medium> allMediums = mediumMan.getAllMedia();
            model.addMedia(allMediums);
        }
    }

    /**
     * refreshes the table with list of films from a selected medium
     */
    public void refreshMovieTable() {
        int selection = jTableMedia.getSelectedRow();
        if (selection != -1) {
            if (lastSelected != selection) {
                lastSelected = selection;
                MediumTableModel model = (MediumTableModel) jTableMedia.getModel();

                if (model.getMediumAt(selection) != null) {
                    chosenMedium = model.getMediumAt(selection);
                    MovieTableModel movieModel = (MovieTableModel) jTableFilms.getModel();

                    // get time in ms 
                    //long t1 = Calendar.getInstance().getTimeInMillis();

                    SwingWorker<List<Movie>, Void> sw = new SwingWorker<List<Movie>, Void>() {

                        @Override
                        protected List<Movie> doInBackground() throws Exception {
                            List<Movie> movies = centralMan.getMoviesOnMedium(chosenMedium);
                            if (workingDialog != null) {
                                workingDialog.dispose();
                            }
                            return movies;
                        }
                    };
                    sw.execute();

                    workingDialog = new WorkingDialog(mainWindow, true);
                    workingDialog.setVisible(true);

                    List<Movie> movies = null;

                    try {
                        movies = sw.get();
                    } catch (InterruptedException | ExecutionException ex) {
                        //Logger.getLogger(WorkingDialog.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    // get time in ms 
                    //long t2 = Calendar.getInstance().getTimeInMillis();
                    //System.out.println("Total time to get data from database: " + ((t2 - t1) / 1000) + " s");

                    movieModel.addMovies(movies);
                }
            }
        } else {
            MovieTableModel mTM = (MovieTableModel) jTableFilms.getModel();
            List<Movie> moviesToDelete = new ArrayList<>();
            for (int i = 0; i < mTM.getRowCount(); i++) {
                moviesToDelete.add(mTM.getMovieAt(i));
            }
            for (Movie m : moviesToDelete) {
                mTM.removeMovie(m);
            }
        }
    }

    /**
     * Setting the Landed Button enabled or disabled. Enabled when a medium is
     * chosen, otherwise disabled.
     *
     * @param state state that will the button have
     */
    public void setLandedButtonActive(boolean state) {
        jLandedButton.setEnabled(state);
        jLandedButton.setText("Lent / Return");
    }

    /**
     * Setting the text on Landed Button. Return to Library will appear when
     * Medium attribute landed is true. Land will appear when otherwise.
     *
     * @param state state the button will have
     */
    public void setLandedButton(boolean state) {
        jLandedButton.setEnabled(true);
        if (state) {
            jLandedButton.setText("Return to Library");
        } else {
            jLandedButton.setText("Lent");
        }
    }

    /**
     * Selects medium to be chosen in a table.
     *
     * @param m chosen medium
     * @return true when other medium is selected
     */
    public boolean selectMedium(Medium m) {
        MediumTableModel mTM = (MediumTableModel) jTableMedia.getModel();
        int max = mTM.getRowCount();
        for (int i = 0; i < max; i++) {
            if (mTM.getMediumAt(i).equals(m)) {
                jTableMedia.changeSelection(i, i, false, false);
                return true;
            }
        }
        return false;
    }

    /**
     * Listener for finding which row of a table was chosen.
     *
     */
    public class SelectionListener implements ListSelectionListener {

        JTable table;

        SelectionListener(JTable table) {
            this.table = table;
        }

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // If cell selection is enabled, both row and column change events are fired
            if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) {
                int selection = this.table.getSelectedRow();
                if (selection == -1) {
                    setLandedButtonActive(false);
                } else {
                    setLandedButtonActive(true);
                    MediumTableModel model = (MediumTableModel) jTableMedia.getModel();
                    setLandedButton(model.getMediumAt(selection).isLended());
                    refreshMovieTable();
                }
            }
        }
    }

    /**
     * Setting a filter for a FileChoser.
     *
     */
    public class ODTFileFilter extends javax.swing.filechooser.FileFilter {

        /**
         * file format for filter
         */
        public final static String ods = "ods";

        @Override
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String ext = null;
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }

            String extension = ext;
            if (extension != null) {
                if ((extension.toLowerCase()).equals(ods)) {
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        }

        @Override
        public String getDescription() {
            return ".ods files";
        }
    }
}
